<!-- 视频创作 -->
<template>
  <div>
    <c-title text="视频创作"></c-title>
    <div class="headTop flex-column">
      <template v-if="!body || !body.id">
        <div class="himg">
          <img :src="`${imgPath}ai-create/ai-create-05.png`" alt="" />
        </div>
        <p class="f-13 color-AAAAB3 m-t-10" style="color: #6E6E79;">{{ premission.body_add_button ? "您还没有数字分身，快去定制一个吧！！！" : "暂无权限创建分身" }}</p>
        <van-button v-if="premission.body_add_button" @click.stop="toDigitalHuman" round type="info" color="var(--themeBaseColor)" style="width: 8.125rem;margin-top: 0.625rem;height: 2.25rem;"
          >新建分身</van-button
        >
      </template>
      <template v-else>
        <div class="bg-fff DigitalHuman-item border-radius-10 border-ffffff-2" style="width: 115px;" @click.stop="onPreviewVideo(body.url)">
          <img v-if="body.cover_img" :src="body.cover_img" alt="" class="border-radius-10 w_h_100" />
          <video v-else :src="body.url" alt="" class="border-radius-10 w_h_100" />
        </div>
        <div class="flex" style="margin-top: 0.625rem;">
          <van-button
            v-if="premission.body_add_button"
            plain
            round
            type="info"
            color="var(--themeBaseColor)"
            style="width: 6.25rem;height: 2.25rem;margin-right: 0.625rem;"
            @click.stop="toDigitalHuman"
            >重新定制</van-button
          >
          <van-button @click.stop="onClickVal('showDigitalHuman', true)" round type="info" color="var(--themeBaseColor)" style="width: 6.25rem;height: 2.25rem;">更换分身</van-button>
        </div>
      </template>
    </div>

    <div style="margin-top: -3.125rem;">
      <van-cell-group inset class="t-l">
        <van-field v-model="name" label="视频名称" placeholder="请输入视频名称" />
        <van-cell title="视频封面" value-class="t-l f-grow-2">
          <van-uploader v-model="fileList" multiple :after-read="afterRead" :max-count="1" @delete="delCover_img" />
        </van-cell>
      </van-cell-group>

      <van-cell-group inset class="m-t-10 bg-fff">
        <van-tabs v-model="drive_type" @change="onChangeTab" line-width="20" color="var(--themeBaseColor)">
          <van-tab title="文本驱动" name="0">
            <div class="margin-10 margin-top-0">
              <div class="border-radius-10">
                <van-field v-model="voice_text" rows="5" autosize type="textarea" placeholder="请输入或粘贴文案" @input="bindVCTextInp" style="background-color: #f5f5f5;"/>
                <!-- <textarea model:value="{{voice_text}}" bindinput="bindVCTextInp" placeholder="请输入或粘贴文案" class="border-radius-10 bg-F8F8F8 padding-10" maxlength="-1" /> -->
              </div>
              <div class="gird-5 m-t-10">
                <div v-for="(item, index) in textConfig" :key="index" class="flex-a-c flex-j-c" @click.stop="onClickVal(item.pop, true)">
                  <i class="iconfont" :class="item.icon"></i>
                  <p class="padding-left-3">{{ item.name }}</p>
                </div>
              </div>
            </div>
          </van-tab>
          <van-tab title="音频驱动" name="1">
            <div class="margin-10 border-radius-10 bg-F8F8F8 flex-column flex-a-c flex-j-sa relative" style="min-height: 170px;">
              <div class="flex-column flex-a-c flex-j-c"  v-if="!hasAudio">
                <!-- @click.stop="getVoice" -->
                <van-uploader accept="audio/mp3,audio/m4a,audio/wav,audio/m4a" :after-read="getVoice">
                    <i class="iconfont icon-jiahao"></i>
                    <p>上传30M以内的音频 mp3、m4a、wav</p>
                </van-uploader>
              </div>

              <div class="t-c" v-if="hasAudio">
                <div class="relative">
                  <img :src="`${imgPath}ai-create/ai-create-09.png`" alt="" style="width: 100px;height: 122px;" />
                  <div class="template-center block-center" @click.stop="onClickAudio"><i class="f-40 iconfont " :class="AudioStatus ? 'icon-pause' : 'icon-play'" style="line-height: 40px;"></i></div>
                </div>
                <div style="margin-top: -20px;">{{ audioDuration }}</div>
              </div>

              <div v-if="Progress && Progress < 100" style="width: 90%;">
                <p>上传音频进度</p>
                <van-progress :percentage="Progress" stroke-width="6px" color="var(--themeBaseColor)" track-color="#ffffff" />
              </div>

              <div @click.stop="resetAudio" class="absolute icon-clone-absolute" v-if="hasAudio">
                <i class="f-13 iconfont icon-guanbi"></i>
              </div>
            </div>
            <!-- <div class="gird-5" style="margin-bottom: 5px;">
              <div class="flex-a-c flex-j-c" @click.stop="onClickVal('showDub', true)">
                <i class="iconfont icon-peiyin"></i>
                <p class="padding-left-3">配音</p>
              </div>
            </div> -->
          </van-tab>
        </van-tabs>
      </van-cell-group>

      <div class="m-t-10 padding-10">
        <div class="t-c" style="display: inline-flex;">
          {{form_tip.tip}}
        </div>
        <div class="m-t-10" style="text-align: left;">注：如合成的视频需进行唇形匹配，合成的视频时长需小于120秒，且不能选择背景音乐，否则不能进行唇形匹配！</div>
        <div class="flex-j-sa m-t-10">
          <van-button @click.stop="toSpaceDetails" plain round color="var(--themeBaseColor)" template style="width: 10rem;">取消</van-button>
          <van-button @click.stop="createVideo" round color="var(--themeBaseColor)" template style="width: 10rem;">提交</van-button>
        </div>
      </div>
    </div>

    <div style="height: 6.25rem;"></div>

    <van-popup v-model="showConfig" class="pop-base-class t-l" closeable position="bottom" round style="background-color: #F5F5F5;">
      <div class="pop-base-title">配置</div>
      <div class="pop-base-content" style="padding: 0;">
        <van-cell-group inset>
          <van-cell title="配音语速" value-class="f-grow-3 overflow-inherit" center>
            <div class="flex-a-c">
              <div style="flex: 1;">
                <van-slider v-model="voice_speech" @change="onDragVS($event, 'voice_speech', 0.5, 2)" bar-height="6px" active-color="var(--themeBaseColor)"></van-slider>
              </div>
              <div class="t-r" style="width: 40px;">{{ video_set.voice_speech }}</div>
            </div>
          </van-cell>
          <van-cell title="配音音量" value-class="f-grow-3 overflow-inherit" center>
            <div class="flex-a-c">
              <div style="flex: 1;">
                <van-slider v-model="voice_volume" @change="onDragVS($event, 'voice_volume', 0, 10)" bar-height="6px" active-color="var(--themeBaseColor)"></van-slider>
              </div>
              <div class="t-r" style="width: 40px;">{{ video_set.voice_volume }}</div>
            </div>
          </van-cell>
          <van-cell title="音乐音量" value-class="f-grow-3 overflow-inherit" center>
            <div class="flex-a-c">
              <div style="flex: 1;">
                <van-slider v-model="video_volume" @change="onDragVS($event, 'video_volume', 0, 10)" bar-height="6px" active-color="var(--themeBaseColor)"></van-slider>
              </div>
              <div class="t-r" style="width: 40px;">{{ video_set.video_volume }}</div>
            </div>
          </van-cell>
        </van-cell-group>
      </div>
      <div class="pop-base-bottom" @click.stop="onClickVal('showConfig', false)">
        <van-button round type="danger" block template color="var(--themeBaseColor)" style="height: 40px;">确认</van-button>
      </div>
    </van-popup>

    <van-popup v-model="showMusic" class="pop-base-class" closeable position="bottom" round style="background-color: #F5F5F5;" @open="afterPopMusic">
      <div class="pop-base-title">选择背景音乐</div>
      <van-tabs id="Music" v-model="activeMusic" @click="onChangeTabMusic" line-width="20" nav-class="tabs-class" color="var(--themeBaseColor)" background="#f5f5f5">
        <van-tab :title="item.name" :name="item.id" v-for="(item, index) in bgm_category_list" :key="index">
          <!-- <scroll-div scroll-y="true" style="height: 50vh;" bindscrolltolower="onPopReachBottom" data-name="getBGMList"> -->
            <div class="pop-base-content">
          <div>
            <div class="flex-column flex-j-c flex-a-c m-t-10" v-if="!BGMList.length">
              <p>该分类暂无音源...</p>
            </div>
            <div class="gird-2 padding-12">
              <div
                class="bg-fff border-radius-10 padding-10 flex-a-c"
                :class="bgm_id == item.id ? 'activeBlock' : ''"
                v-for="(item, index) in BGMList"
                :key="index"
                @click.stop="selectVal('bgm_id', item.id)"
              >
                <div class="img-radius music-icon t-c" @click.stop="onClickMusic(item.url, 'BGMIndex', index)">
                  <i class="iconfont" :class="BGMIndex == index && AudioStatus == 1 ? 'icon-pause' : 'icon-play'"></i>
                </div>
                <div class="f-14 f-grow-1 padding-left-6 line-height-16">{{ item.name }}</div>
              </div>
            </div>
          </div>
        </div>
          <!-- </scroll-div> -->
        </van-tab>
      </van-tabs>
      <div class="pop-base-bottom flex">
        <van-button @click.stop="onClickVal('bgm_id', null)" plain round type="danger" template color="var(--themeBaseColor)" style="height: 40px;width: 100%;margin-right: 6px;">重置</van-button>
        <van-button @click.stop="onClickVal('showMusic', false)" round type="danger" template color="var(--themeBaseColor)" style="height: 40px;width: 100%;">确认</van-button>
      </div>
    </van-popup>
    <audio ref="audioRef" style="opacity: 0;" @loadedmetadata="handleMetadataLoaded" controls @ended="ended" v-if="innerAudioContext && innerAudioContext.src">
        <source :src="innerAudioContext ? innerAudioContext.src : ''" type="audio/mpeg">
      </audio>
    <van-popup v-model="showCopywriter" @close="getInterestsTip" class="pop-base-class t-l" closeable position="bottom" round style="background-color: #F5F5F5;">
      <div class="pop-base-title">文案</div>
      <div class="pop-base-content">
        <van-cell-group inset class="m-t-10 bg-fff">
          <van-cell title="角色选择" :border="false" use-label-slot>
            <template #label>
              <div class="gird-4">
                <div
                  v-for="(item, index) in role_list"
                  :key="index"
                  style="padding: 0.625rem 0;"
                  class="bg-F8F8F8 border-radius-10 writer-item"
                  :class="selectRole.id == item.id ? 'activeBlock' : ''"
                  @click.stop="onClickVal('selectRole', item)"
                >
                  {{ item.name }}
                </div>
              </div>
            </template>
          </van-cell>
        </van-cell-group>

        <van-cell-group inset class="m-t-10 bg-fff">
          <van-cell title="字数要求" :value="words.content || '选择字数'" is-link @click="onClickVal('showWords', true)" />
        </van-cell-group>

        <van-cell-group inset class="m-t-10 bg-fff">
          <van-cell title="主题描述" value="试试范文" value-class="themeColor" @click="getEssay" :border="false" />
          <div class="margin-10 border-radius-10 bg-F8F8F8" style="margin-top: 0!important">
            <van-field v-model="theme" rows="5" autosize type="textarea" placeholder="请输入主题内容" @input="bindVCTextInp" style="background-color: #f5f5f5;"/>
            <!-- <textarea model:value="{{theme}}" placeholder="请输入主题内容" class="padding-10" maxlength="-1" /> -->
            <div class="flex-j-sb flex-a-c padding-10 color-AAAAB3">
              <div class="flex-a-c" @click.stop="onClickVal('theme', '')"><i class="iconfont icon-fontclass-shanchu"></i> 清空</div>
              <!-- <div>0/200</div> -->
            </div>
          </div>
        </van-cell-group>
      </div>
      <div class="pop-base-bottom t-c" @click.stop="showCopywriter = false">
        <div style="margin-bottom: 6px;display: inline-flex;">
          {{form_tip.tip}}
        </div>
        <!-- <div v-else class="t-c" style="margin-bottom: 6px;">您还未获得文案创作的权益，暂时无法生成文案</div> -->
        <!-- <div class="computed-box" v-if="form_tip.open_comput_power" style="margin-top: 0">
          <div style="margin-bottom: 0.5rem">{{form_tip.tip}}</div>
        </div> -->
        <van-button :disabled="!paperwork_unused" block color="var(--themeBaseColor)" @click.stop="createWords" round type="danger" template style="height: 40px;">生成文案</van-button>
      </div>
    </van-popup>

    <van-popup v-model="showWords" class="pop-base-class" position="bottom" round style="background-color: #F5F5F5;">
      <van-picker show-toolbar title="选择字数" :columns="words_scope_list" value-key="content" @confirm="confirmWords" @cancel="onClickVal('showWords', false)" />
    </van-popup>

    <van-popup v-model="showDigitalHuman" class="pop-base-class" position="bottom" round style="background-color: #F5F5F5;" @open="afterDigitalHumanPop">
      <div class="pop-base-title">选择数字分身</div>

      <!-- <scroll-div scroll-y="true" style="height: 50vh;padding: 0 0.625rem;box-sizing: border-box;" bindscrolltolower="onPopReachBottom" data-name="DigitalHumanPop"> -->
      <div class="pop-base-content" style="padding: 0 0.625rem;">
        <div class="gird-3">
          <div class="bg-fff padding-6 DigitalHuman-item border-radius-10" v-if="premission.body_add_button" style="width: 100%;">
            <div class="border-radius-10 bg-F8F8F8 flex-column flex-j-c t-c w_h_100" @click.stop="toDigitalHuman">
              <i class="iconfont icon-jiahao"></i>
              <div>立即定制</div>
            </div>
          </div>
          <div
            class="bg-fff DigitalHuman-item border-radius-10 border-ffffff-2"
            :class="body_id == item.id ? 'activeBlock' : ''"
            v-for="(item, index) in bodyList"
            :key="index"
            @click.stop="selectBody(item)"
          >
            <div class="border-radius-10 w_h_100">
              <img v-if="item.cover_img" :src="item.cover_img" alt="" class="w_h_100" />
              <video v-else :src="item.url" class="w_h_100" />
            </div>
          </div>
        </div>
        <div style="height: 40px;"></div>
      </div>
      <!-- </scroll-div> -->

      <div class="pop-base-bottom" @click.stop="selectVal('showDigitalHuman', false)">
        <van-button round type="danger" block color="var(--themeBaseColor)" template style="height: 40px;">确认</van-button>
      </div>
    </van-popup>

    <van-popup v-model="showDub" class="pop-base-class" position="bottom" round style="background-color: #F5F5F5;" @open="resizeDub">
      <div class="pop-base-title">选择配音</div>
      <van-tabs id="Dub" v-model="active" line-width="20" @change="showDubPopup" nav-class="tabs-class" color="var(--themeBaseColor)" background="#f5f5f5">
        <van-tab :title="item.title" v-for="(item, index) in audio_list" :key="index">
          <div class="voice-clone-tab" v-if="active === 0"> 
            <span :class="audio_type === 0 ? 'clone-tabs active-clone-tabs' : 'clone-tabs'" @click="clickAudioType(0)">声音克隆({{audio_sjt_count}})</span>
            <span :class="audio_type === 1 ? 'clone-tabs active-clone-tabs' : 'clone-tabs'"  @click="clickAudioType(1)">声音克隆CV版({{audio_cv_count}})</span>
          </div>
          <div style="height: 50vh; overflow-y: scroll;">
            <div class="gird-2 padding-12">
              <div
                class="bg-fff border-radius-10 padding-10 flex-a-c"
                :class="voice_id == child.voice_id ? 'activeBlock' : ''"
                v-for="(child, idx) in item.list"
                :key="idx"
                @click.stop="selectVal('voice_id', child.voice_id)"
              >
                <div class="img-radius music-icon t-c" @click.stop="onClickMusic(child.url, 'dubIndex', idx)">
                  <i class="iconfont" :class="dubIndex == idx && AudioStatus == 1 ? 'icon-pause' : 'icon-play'"></i>
                </div>
                <div class="f-14 f-grow-1 padding-left-6 line-height-16">{{ child.name }}</div>
              </div>
            </div>

            <div class="flex-column flex-j-c flex-a-c" v-if="!item.list.length">
              <img :src="`${imgPath}ai-create/ai-create-06.png`" alt="" style="width: 115px;" />
              <p>暂无发音人</p>
            </div>
          </div>
        </van-tab>
      </van-tabs>

      <div class="pop-base-bottom flex">
        <van-button round type="danger" template color="var(--themeBaseColor)" style="height: 40px;width: 100%;margin-right: 6px;" @click.stop="onClickVal('showDub', false)">确认</van-button>
      </div>
    </van-popup>

    <van-popup v-model="previewMedia" position="center" round style="background-color: #000;width: 100%;" @close="oncloseMedia">
      <video :src="previewMediaUrl" controls style="width: 100%;"></video>
    </van-popup>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imgPath: "",
      business_id: 0,
      name: "", //封面
      drive_type: "0", //驱动类型：0=文案；1=音频
      fileList: [],
      voice_speech: 35, //配音语速，默认1.0。取值：[0.5,2.0]，支持小数
      voice_volume: 50,
      video_volume: 2,
      paperwork_total: 0,
      minute: 0,

      activeMusic: '0',
      selectRole: {},
      showWords: false,
      bodyList: [],

      textConfig: [
        {
          icon: "icon-peizhi",
          name: "配置",
          pop: "showConfig"
        },
        //  {
        //   icon: 'icon-duanju',
        //   name: '断句'
        // },
        {
          icon: "icon-yinle",
          name: "音乐",
          pop: "showMusic"
        },
        {
          icon: "icon-icon_dingdan_11",
          name: "文案",
          pop: "showCopywriter"
        },
        {
          icon: "icon-peiyin",
          name: "配音",
          pop: "showDub"
        }
      ],
      showConfig: false,
      actions: [
        {
          name: "中文"
        },
        {
          name: "英文"
        }
      ],
      showMusic: false,
      showCopywriter: false,
      showDigitalHuman: false,

      role_list: [],
      previewMedia: false,
      previewMediaUrl: "",
      video_set: {
        voice_speech: 1.0,
        voice_volume: 1.0,
        video_volume: 1.0
      },
      body: {},
      audio_list: [],
      BGMList: [],
      premission: {},
      essayList: [],
      selectEssayIndex: 0,
      theme: "",
      words: {},
      audioDuration: "00:00",
      hasAudio: false,
      Progress: 0,
      innerAudioContext: null,
      AudioStatus: 0,
      BGMListPage: 1,
      dubIndex: 0,
      BGMIndex: 0,
      BGMList_finished: false,
      voice_text: "",
      video_duration_unused: 0,
      paperwork_unused: 0,
      body_id: 0,
      audio_id: 0,
      voice_id: 0,
      bgm_id: 0,
      active: 0,
      showDub: false,
      audio_type: 0,
      audio_cv_count: 0,
      audio_sjt_count: 0 ,
      form_tip: {}
    };
  },

  created() {
    this.form = {};
    this.business_id = this.$route.query.business_id;
    this.body_id = this.$route.query.body_id;
    this.getData();
  },

  components: {},

  computed: {},

  mounted() {
    this.initData();
    this.getInterestsTip();
  },

  methods: {
    onClickVal(name, val) {
      this[name] = val;
      if (name == "selectRole") {
        this.essayList = null;
      }
      this.AudioPause();
      this.getInterestsTip();
    },
    selectVal(name, val) {
      this[name] = val;
      this.form[name] = val;
    },
    async getData(type) {
      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.create.video",
        {
          body_id: this.body_id || 0,
          business_id: this.business_id || 0,
          audio_type: this.audio_type
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.imgPath = this.$store.state.imgPath;
      Object.assign(this, data);
      if(type !== 'clickAudioType') {
        this.getWorkData();
      }
      if (data.body && data.body.id) {
        this.form.body_id = data.body.id;
      }
    },
    async getWorkData() {
      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.create.paperwork",
        {
          business_id: this.business_id || 0
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      if (!result) return app.tips(msg);
      Object.assign(this, data);
    },

    //视频封面上传
    afterRead(e, flag) {
      e.status = "uploading";
      e.message = "上传中...";
      let fd = new FormData();

      if (flag === true) {
        fd.append("file", e); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      } else {
        fd.append("file", e.file); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      }
      let That = this;
      let uploadUrl = this.fun.getRealUrl("upload.uploadPic", {});
      axios
        .post(uploadUrl, fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(response => {
          let responseData = response.data;
          if (responseData.result === 1) {
            e.status = "done ";
            That.form.cover_img = responseData.data.img;
          } else {
            this.$toast(responseData.msg);
            e.status = "failed";
            e.message = "上传失败";
          }
        })
        .catch(error => {
          this.$toast.clear();
        });
    },
    delCover_img() {
      this.fileList = [];
      this.form.cover_img = '';
    },
    onChangeTab(e) {
      this.form.voice_text = this.drive_type;
      this.form.drive_type = this.drive_type;
    },
    onPreviewVideo(url) {
      this.previewMediaUrl = url;
      this.previewMedia = true;
    },
    oncloseMedia() {
      this.previewMedia = false;
      this.previewMediaUrl = "";
    },
    getVoice(e) {
      let uploadForm = new FormData();
      uploadForm.append("count", 1);
      uploadForm.append("file", e.file);
      this.Progress = 0
      this.uploadAudioM(uploadForm);
      // axios
      //   .post(this.fun.getRealUrl("upload.uploadPic&upload_type=audio"), uploadForm,{
      //     onUploadProgress: (onUploadProgress) => {
      //       this.Progress = Math.round((onUploadProgress.loaded * 100) / onUploadProgress.total)
      //     }
      //   })
      //   .then(
      //     ({data}) => {
      //       this.form.voice_url = data.data.img;
      //       this.setAudioURL(data.data.img_url);
      //       this.hasAudio = true
      //     }
      //   )
      //   .catch(() => {

      //   });
    },
    uploadAudioM(videoData) {
      this.Progress = 0
      this.AudioStatus = "AudioPlay"
      this.audioDuration = "00:00"
      this.innerAudioContext = null
      let uploadLoading = this.$toast.loading({
        message: "上传音频中",
        duration: 0
      });
      axios
        .post(this.fun.getRealUrl("upload.uploadPic&upload_type=audio"), videoData,{
          onUploadProgress: (onUploadProgress) => {
            this.Progress = Math.round((onUploadProgress.loaded * 100) / onUploadProgress.total) == 100 ? 99 : Math.round((onUploadProgress.loaded * 100) / onUploadProgress.total)
          }
        })
        .then(
          ({data}) => {
            this.form.voice_url = data.data.img;
            this.setAudioURL(data.data.img_url);
            this.hasAudio = true
            this.$toast("上传成功");
            uploadLoading.clear();
            this.Progress = 100
          }
        )
        .catch(() => {
          uploadLoading.clear();
        });
    },
    setAudioURL(src) {
      setTimeout(() => {
        this.innerAudioContext = {}
        this.innerAudioContext.src = src;
        console.log(this.innerAudioContext,'this.innerAudioContextthis.innerAudioContext');
        this.AudioPlay();
      }, 10);
    },
    // getAudioDuration() {
    //   if (this.showMusic || this.showDub || this.drive_type == 0) return;
    //   if (!this.form.video_duration) {
    //     let _duration = Math.floor(this.innerAudioContext.duration); // 取整秒数
    //     this.form.video_duration = _duration;
    //     this.audioDuration = this.formatDuration(_duration);
    //     this.minCreatComponent();
    //   }
    // },
    formatDuration(duration) {
      // 将秒数转为 MM:ss  分钟：秒数
      const totalSeconds = duration;
      const minutes = Math.floor(totalSeconds / 60);
      const seconds = totalSeconds % 60;

      const minutesString = minutes.toString().padStart(2, "0");
      const secondsString = seconds.toString().padStart(2, "0");

      return `${minutesString}:${secondsString}`;
    },
    AudioPlay() {
      // this.innerAudioContext.play();
      this.$nextTick(() => {
        const audio = this.$refs.audioRef;
        // 调用播放方法
        audio.play();
        this.AudioStatus = 1;
      })
    },
    formatSeconds(seconds) {
        const date = new Date(seconds * 1000); // 将秒转换为毫秒
        const hh = date.getUTCHours().toString().padStart(2, '0');
        const mm = date.getUTCMinutes().toString().padStart(2, '0');
        const ss = date.getUTCSeconds().toString().padStart(2, '0');
        return `${hh}:${mm}:${ss}`;
    },
    AudioPause() {
      try {
        this.$nextTick(() => {
          const audio = this.$refs.audioRef;
          if(!audio) {return}
          // 调用播放方法
          audio.pause();
          this.AudioStatus = 0;
        })
      } catch (error) {
        console.log("AudioPause error", error);
      }
    },
    ended() {
      this.AudioStatus = 0;
    },
    handleMetadataLoaded() {
      this.$nextTick(() => {
          const audio = this.$refs.audioRef;
          this.audioDuration = audio && audio.duration ? this.formatSeconds(audio.duration) : "00:00"
          console.log(audio.duration,88888);
          this.form.video_duration = audio ?   audio.duration : 0;
          this.minCreatComponent();
      })
    },
    onClickAudio() {
      let name = this.AudioStatus ? "AudioPause" : "AudioPlay";
      this[name]();
      if(name == "AudioPlay") {
        this.AudioPlay();
      }else {
        this.AudioPause();
      }
      console.log(name,this.AudioStatus ,'thisthis');
    },
    resetAudio() {
      this.form.video_duration = null;
      this.form.voice_url = null;
      this.hasAudio = false;
      this.AudioPause();
    },
    initData() {
      this.video_set.voice_speech = this.mapVSSliderValue(this.voice_speech, 0.5, 2.0);
      this.video_set.voice_volume = this.mapVSSliderValue(this.voice_volume, 0, 10.0);
      this.video_set.video_volume = this.mapVSSliderValue(this.video_volume, 0, 10.0);
      // if (!this.innerAudioContext) {
      //   this.innerAudioContext = wx.createInnerAudioContext({
      //     useWebAudioImplement: false
      //   });
      //   this.innerAudioContext.autoplay = true; //设置自动播放
      //   this.innerAudioContext.onTimeUpdate(res => {
      //     this.getAudioDuration();
      //   });
      //   this.innerAudioContext.onPlay(res => {
      //     this.setData({
      //       AudioStatus: 1 //正在播放
      //     });
      //   });
      //   this.innerAudioContext.onPause(res => {
      //     this.setData({
      //       AudioStatus: 0 //暂停播放
      //     });
      //   });
      //   this.innerAudioContext.onEnded(res => {
      //     this.setData({
      //       AudioStatus: 0 //播放完毕
      //     });
      //   });
      // }
    },
    bindVCTextInp() {
      this.minCreatComponent();
    },
    minCreatComponent() {
      // 预计消耗时长计算
      let minute = 0;
      if (this.drive_type == 0) {
        // 文本驱动计算：实际字数 * （60 / 180）/ 语速
        let text = this.voice_text.length || 1;
        minute = text / 180 / this.video_set.voice_speech;
      } else {
        minute = this.form.video_duration / 60;
      }
      minute = Math.max(1, Math.ceil(minute));
      this.minute = minute;
      this.getInterestsTip();
    },
    onDragVS(value, name, min, max) {
      this[name] = value;
      this.video_set[name] = this.mapVSSliderValue(value, min, max);
      if (name == "voice_speech") {
        this.minCreatComponent(); //重新计算消耗的时长
      }
    },
    mapVSSliderValue(oldValue, newMin = 0, newMax = 10) {
      const oldMin = 0;
      const oldMax = 100;
      const newValue = ((oldValue - oldMin) / (oldMax - oldMin)) * (newMax - newMin) + newMin;
      return parseFloat(newValue.toFixed(1)); // 保留一位小数并转换回数字
    },
    resizeDub() {
      // this.selectComponent("#Dub").resize();
    },
    onChangeTabMusic(event) {
      this.AudioStatus = 0;
      this.innerAudioContext = null;
      this.BGMList_finished = false;
      this.BGMListPage = 1;
      this.BGMList = [];
      this.getBGMList();
    },
    afterPopMusic() {
      if (this.BGMList && this.BGMList.length) return;
      this.getBGMList();
    },
    async getBGMList() {
      if (this.BGMList_finished) return;
      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.create.video.get-bgm-list",
        {
          category_id: this.activeMusic || "",
          business_id: this.business_id || 0,
          page: this.BGMListPage || 1
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      let BGMList = this.BGMList || [];
      this.BGMList = BGMList.concat(data.data);
      if (data.current_page == data.last_page) {
        return (this.BGMList_finished = true);
      }
      this.BGMListPage = data.current_page + 1;
    },
    async getEssay() {
      // 获取范文
      if (!this.selectRole.id) {
        this.$toast("请先选择角色");
        return;
      }
      if (this.essayList && this.essayList.length) {
        this.selectEssayIndex = this.selectEssayIndex == this.essayList.length - 1 ? 0 : (this.selectEssayIndex += 1);
        this.theme = this.essayList[this.selectEssayIndex].content;
        return;
      }

      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.create.paperwork.get-essay-list",
        {
          role_id: this.selectRole.id,
          business_id: this.business_id || 0
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.essayList = data;
      this.selectEssayIndex = 0;
      this.theme = this.essayList.length ? this.essayList[0].content : '';
    },
    confirmWords(value, index) {
      this.words = value;
      this.showWords = false;
    },
    containsEmoji(str) {
      // Emoji表情的正则表达式
      const emojiPattern = /[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}]/gu;
      return emojiPattern.test(str);
    },
    async createWords() {
      // 生成文案
      if (!this.selectRole.id) {
        this.$toast("请先选择角色");
        return;
      }
      if (!this.words.content) {
        this.$toast("请先选择字数");
        return;
      }
      if (!this.theme) {
        this.$toast("请输入主题内容");
        return;
      }
      if (this.containsEmoji(this.theme)) {
        this.$toast("不支持包含emoji表情的文本");
        return;
      }
      this.$toast.loading({
        message: "生成文案中...",
        forbidClick: true
      });
      let { result, msg, data } = await $http.post(
        "plugin.ai-create.frontend.controllers.create.paperwork.create",
        {
          words_limit: this.words.content,
          character: this.selectRole.name,
          theme: this.theme,
          business_id: this.business_id || 0
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.paperwork_total += 1;
      this.voice_text = data.content;
      this.showCopywriter = false;
      this.paperwork_unused = this.paperwork_unused - 1;
    },
    async createVideo() {
      let { name, voice_id, bgm_id, voice_text, drive_type, video_set, selectRole, paperwork_total } = this;

      if (!this.form.body_id) {
        this.$toast("请先选择数字分身");
        this.showDigitalHuman = true;
        return;
      }
      if (Number(drive_type) == 0) {
        if (!name) {
          this.$toast("请填写视频名称");
          return;
        }
        if (!voice_text) {
          this.$toast("请填写文案");
          return;
        }
      }

      if (Number(drive_type) == 1 && !this.form.voice_url) {
        this.$toast("请上传音频");
        return;
      }
      if (Number(drive_type) == 0 && !voice_id) {
          if (!voice_id) {
            this.$toast("请选择配音");
            this.showDub = true;
            return;
          }
      }

      if (this.containsEmoji(this.voice_text)) {
        this.$toast("不支持包含emoji表情的文本");
        return;
      }
      // this.audioDuration
      this.form.role_name = selectRole.name;
      this.form.paperwork_total = paperwork_total;
      this.form = {
        ...this.form,
        name,
        voice_id,
        bgm_id,
        voice_text,
        drive_type,
        video_set
      };
      let { result, msg, data } = await $http.post(
        "plugin.ai-create.frontend.controllers.create.video.create",
        {
          form: this.form,
          business_id: this.business_id
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.toSpaceDetails();
    },
    toSpaceDetails() {
      this.$router.push(this.fun.getUrl("aiCreatePerSpace", {}, { business_id: this.business_id }));
    },
    toDigitalHuman() {
      this.$router.push(this.fun.getUrl("aiCreateDigitalHuman", {}, { business_id: this.business_id }));
    },
    afterDigitalHumanPop() {
      this.bodyList = [];
      this.bodyList_finished = false;
      this.bodyListPage = 1;
      // if (this.data.bodyList && this.data.bodyList.length) return;
      this.DigitalHumanPop();
    },
    async DigitalHumanPop() {
      if (this.bodyList_finished) return;
      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.create.video.get-body-list",
        {
          business_id: this.business_id,
          page: this.bodyListPage || 1
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      let bodyList = this.bodyList || [];
      this.bodyList = bodyList.concat(data.data);

      if (data.current_page == data.last_page) {
        return (this.bodyList_finished = true);
      }
      this.bodyListPage = data.current_page + 1;
    },
    selectBody(item) {
      this.form.body_id = item.id;
      this.body_id = item.id;
      this.body = item;
    },
    onPopReachBottom(e) {
      let { name } = e.currentTarget.dataset;
      if (name) this[name]();
    },
    onClickMusic(url, name, index) {
      if (!url) return;
      this[name] = index;
      this.innerAudioContext = null
      this.setAudioURL(url);
    },
    showDubPopup() {
      this.$nextTick(() => {
        const audio = this.$refs.audioRef;
        // 调用播放方法
        audio.pause();
        this.AudioStatus = 0;
        this.innerAudioContext = null
      })
    },
    clickAudioType(audio_type) {
      this.audio_type = audio_type;
      this.$nextTick(() => {
        const audio = this.$refs.audioRef;
        // 调用播放方法
        audio.pause();
        this.AudioStatus = 0;
        this.innerAudioContext = null
      })
      this.getAudioCount();   
      this.getData('clickAudioType');
    },
    async getAudioCount(){
      let { result, msg, data } = await $http.post(
        "plugin.ai-create.frontend.controllers.audio.index.get-audio-count",
        {
          business_id: this.business_id || 0,
        },
        "."
      );
      if (!result) return;
      this.audio_cv_count = data.audio_cv_count
      this.audio_sjt_count = data.audio_sjt_count
    },
    async getInterestsTip() {
      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.center.index.get-Interests-tip",
        {
          business_id: this.$route.query.business_id || 0,
          interests_type: this.showCopywriter ? 5 :  4,
          minute: this.minute
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.form_tip = data;
      console.log(result, msg, data,2222,this.form_tip)
    },
  }
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
.pop-base-class .pop-base-title {
  margin: 18px 12px 12px !important;
  font-size: 1rem !important;
  font-weight: bold !important;
  text-align: left !important;
}

.pop-base-class .pop-base-content {
  min-height: 45vh;
  max-height: 60vh;
  overflow: scroll;
  padding: 0 0rem 3.75rem;
}

.pop-base-class .pop-base-bottom {
  padding: 0.625rem 0.875rem;
  background: #ffffff;
}

.themeColor {
  color: var(--themeBaseColor) !important;
}

.color-00001C {
  color: #00001c;
}

.color-AAAAB3 {
  color: #aaaab3;
}

.color-F15353 {
  color: #f15353;
}

.bg-fff {
  background-color: #ffffff;
}

.bg-F8F8F8 {
  background-color: #f8f8f8;
}

.bg-E5EEFE {
  background-color: #e5eefe;
}

.overflow-inherit {
  overflow: inherit !important;
}

.img-radius {
  border-radius: 50%;
  overflow: hidden;
}

.border-radius-10 {
  border-radius: 0.625rem;
  overflow: hidden;
}

.tabs-custom-class {
  background-color: #f5f5f5;
}

.tabs-custom-class .van-tabs__line {
  bottom: 6px !important;
  width: 20px !important;
}

.relative {
  position: relative;
}

.absolute {
  position: absolute !important;
}

.block-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 56px;
  color: #ffffff;
}

.icon-clone-absolute {
  width: 25px;
  height: 20px;
  top: 0;
  right: 0;
  background: #7b7b89;
  border-radius: 0px 8px 0px 8px;
  color: #ffffff;
  text-align: center;
}

.line-height-16 {
  line-height: 1rem;
}

.m-t-10 {
  margin-top: 0.625rem !important;
}

.margin-10 {
  margin: 0.625rem;
}

.padding-10 {
  padding: 0.625rem;
  width: 100%;
}

.padding-6 {
  padding: 0.375rem;
}

.padding-12 {
  padding: 0.75rem;
}

.padding-top-12 {
  padding-top: 0.75rem;
}

.padding-bottom-12 {
  padding-bottom: 0.75rem;
}

.padding-left-3 {
  padding-left: 0.1875rem;
}

.padding-left-6 {
  padding-left: 0.375rem;
}

.gird-2 {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-row-gap: 0.5rem;
  grid-column-gap: 0.5rem;
}

.gird-3 {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-row-gap: 0.625rem;
  grid-column-gap: 0.625rem;
}

.gird-4 {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  text-align: center;
  grid-row-gap: 0.5rem;
  grid-column-gap: 0.5rem;
}

.gird-5 {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  text-align: center;
}

.border-ffffff-2 {
  border: 0.125rem solid #ffffff;
}

.headTop {
  padding: 1.5rem 0.75rem 4.6875rem;
  background-image: -webkit-gradient(linear, left top, left bottom, from(var(--themeBaseColor)), to(#f5f5f5));
  background-image: -webkit-linear-gradient(var(--themeBaseColor), #f5f5f5);
  background-image: linear-gradient(var(--themeBaseColor), #f5f5f5);
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.headTop .himg {
  width: 7.1875rem;
  height: 7.1875rem;
  background: linear-gradient(180deg, #ffffff 0%, rgba(255, 255, 255, 0) 100%);
  border-radius: 50%;
  overflow: hidden;
  margin: 0 auto;
}

.headTop .himg img {
  width: 100%;
  height: 100%;
  border-radius: 100%;
}

.music-icon {
  width: 32px;
  height: 32px;
  line-height: 32px;
  color: var(--themeBaseColor);
  position: relative;
}
.music-icon::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: var(--themeBaseColor);
  opacity: 0.15;
}

.DigitalHuman-item {
  min-height: 3.35rem;
  border-width: 0.05rem !important;
}

.w_h_100 {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.DigitalHuman-item img {
  display: block;
  margin: 0;
  object-fit: contain;
}
.writer-item {
  position: relative;
}
.writer-item.activeBlock {
  color: var(--themeBaseColor);
}
.writer-item.activeBlock::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: var(--themeBaseColor);
  opacity: 0.1;
}
.activeBlock {
  border: 1px solid var(--themeBaseColor);
}
.voice-clone-tab {
  margin: 0.9rem 0.75rem 0.2rem 0.6rem;
  display: flex;
}
.clone-tabs {
  font-size: 0.9375rem;
  background: #FFFFFF;
  border-radius: 0.5rem;
  padding: 0.36rem 0.7rem;
  margin-right: 1rem;
  font-weight: 500;
  color: #6E6E79;
}
.active-clone-tabs {
  background: #DCE5F5;
  color: #015EF5;
}
.computed-box {
  margin-top: 0.875rem;
  font-weight: 400;
  font-size: 0.8125rem;
  color: #6E6E79;
  line-height: 1.3125rem;
  padding: 0 0.625rem;
  .computed-tip {
    color: #015EF5;
  }
}
</style>
